package com.innovation.chengzhangriji.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.DiscoverSaveComment;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.DiscoverCommentResponse;
import com.innovation.chengzhangriji.http.DiscoverContentResponse;
import com.innovation.chengzhangriji.http.DiscoverLikeResponse;
import com.innovation.chengzhangriji.http.DiscoverResponse;
import com.innovation.chengzhangriji.http.DiscoverSaveResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.DiscoverActivity;
import com.innovation.chengzhangriji.ui.DiscoverCommentActivity;
import com.innovation.chengzhangriji.ui.event.BaseEvent;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.orhanobut.logger.Logger;

import org.apache.http.Header;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;

public class LocalCommentService extends Service {

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {

        final LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        // 获取最新评论
        Client.requestDiscoverComment(this, phone, token, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Logger.d(value.toString());
                // 解析 评论数据
                DiscoverSaveResponse response = get(value.toString(), DiscoverSaveResponse.class);
                if (response == null || (response.getComment().length == 0 && response.getLike().length == 0 && response.getDelete().length == 0)) {
                    sendCheckComplete();
                    return;
                }
                // 存储本地
                storeCommentToLocal(response, loginInfo);
                if (intent != null && intent.getExtras() != null) {
                    // 发送通知
                    if (!TextUtils.isEmpty(intent.getExtras().getString("msg"))) {
                        sendNewCommentNotification(intent.getExtras().getString("msg"), intent.getIntExtra("badge", 0));
                    }
                    // 发送检查通知
                    else if (intent.getExtras().getBoolean("autoCheck")) {
                        sendCheckComplete();
                    }
                } else {
                    // 发送广播
                    sendNewCommentBroadcast();
                }
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                sendCheckComplete();
            }
        });

        return super.onStartCommand(intent, flags, startId);
    }

    // 发送检查完成的通知
    private void sendCheckComplete() {
        BaseEvent event = new BaseEvent();
        event.setType(BaseEvent.TYPE_CHECK_NEW_COMMENT);
        EventBus.getDefault().post(event);
    }

    // 将评论存储到本地
    private void storeCommentToLocal(DiscoverSaveResponse response, LoginInfo loginInfo) {
        ArrayList<DiscoverSaveComment> comments = new ArrayList<DiscoverSaveComment>();
        // 普通评论
        addComment(response.getComment(), comments, 1, loginInfo.getUserID());
        // 点赞评论
        addComment(response.getLike(), comments, 1, loginInfo.getUserID());
        // 保存评论到数据库
        DatabaseManager.getInstance(getBaseContext()).insertOrReplaceDiscoverSaveCommentInTx(comments);
        // 下载 日记信息
        requestDiscover(comments, loginInfo);
    }

    // 发送广播
    public void sendNewCommentBroadcast() {
        // 设置有新评论
        Config.setHasNewComment(this, true);

//        Intent intent = new Intent(Config.ACTION_NEW_COMMENT_DOWNLOAD_SUCCEED);
//        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        EventBus.getDefault().post(new BaseEvent(BaseEvent.TYPE_NEW_COMMENT_DOWNLOAD_SUCCESS));
    }

    // 发送通知
    public void sendNewCommentNotification(String msg, int badge) {
        // 设置有新评论
        Config.setHasNewComment(this, true);

        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification)
                .setContentTitle(this.getString(R.string.app_name))
                .setContentText(msg);
        builder.setAutoCancel(true);
        builder.setDefaults(Notification.DEFAULT_ALL);
        builder.setLights(Color.BLUE, 300, 300);
        Intent resultIntent = new Intent(this, DiscoverCommentActivity.class);
//        resultIntent.putExtra("newComment", true);
//        resultIntent.putExtra(Config.EXTRA_CAN_BACK, false);
//        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this).addNextIntentWithParentStack(resultIntent);
        PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = builder.build();
        try {
            notification.number = badge;
            // MIUI Badge
            Field field = notification.getClass().getDeclaredField("extraNotification");
            Object extraNotification = field.get(notification);
            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
            method.invoke(extraNotification, badge);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mNotificationManager.cancelAll();
        mNotificationManager.notify(0, notification);
    }

    // 请求日记信息
    private void requestDiscover(ArrayList<DiscoverSaveComment> comments, final LoginInfo loginInfo) {
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        for(int i = 0; i < comments.size(); i++) {
            final DiscoverSaveComment comment = comments.get(i);
            final String diaryId = comment.getDiaryID();
            Client.requestSingleDiscover(this, phone, token,diaryId, new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    Logger.json(value.toString());
                    DiscoverResponse response = get(value.toString(), DiscoverResponse.class);
                    if (response == null || response.getContent() == null) {
                        // 日记已被删除, 删除日记及所有评论
                        DatabaseManager.getInstance(LocalCommentService.this.getApplicationContext()).deleteDiscover(diaryId);
                        return;
                    }
                    // 提前下载音频
                    if(response.getContent().getType() == 3) {
                        downloadAudio(response.getContent().getDiaryId(), response.getContent().getAudio());
                    }
                    // 保存日记到本地数据库
                    storeDiscoverToLocal(response.getContent());
                    // 保存日记的评论到本地数据库
                    storeDiscoverCommentToLocal(response, loginInfo);
                }
            }, new Client.NetworkUnavailableListener() {
                @Override
                public void networkUnavailable() {

                }
            });
        }
    }

    // 添加普通评论
    private void addComment(DiscoverCommentResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from, String userId) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            if(responses[i].getCommentState() == 0) {
                // 删除本地评论
                DatabaseManager.getInstance(this.getApplicationContext()).deleteComment(responses[i].getId());
                return;
            }
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(1);
            comment.setContent(responses[i].getComment());
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getCommentState());
            comment.setUserID(responses[i].getCommentId());
            comment.setReplyUserID(responses[i].getTargetUserId());
            comment.setReplyNickname(responses[i].getTargetNickname());
            comment.setUserNickname(responses[i].getCommentNickname());
            comment.setReplyIdentity(responses[i].getTargetId());
            comment.setUserHeadUrl(responses[i].getCommentHeadUrl());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getCommentName());
            comment.setReplyMemberName(responses[i].getTargetName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(userId);
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    // 添加点赞评论
    private void addComment(DiscoverLikeResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from, String userId) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            if(responses[i].getLikeState() == 0) {
                DatabaseManager.getInstance(this.getApplicationContext()).deleteComment(responses[i].getId());
                continue;
            }
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(2);
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getLikeState());
            comment.setUserID(responses[i].getLikeId());
            comment.setUserHeadUrl(responses[i].getLikeHeadUrl());
            comment.setUserNickname(responses[i].getLikeNickname());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getLikeName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(userId);
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    // 下载音频
    private void downloadAudio(final String diaryId, String audioUrl) {
        if(audioUrl == null) {
            return;
        }
        int start = audioUrl.indexOf(Config.AUDIO);
        if(start == -1) {
            return;
        }
        String subUrl = audioUrl.substring(start);
        File file = new File(getExternalCacheDir(), String.valueOf(subUrl.hashCode()));
        if (!file.exists()) {
            Client.downloadFile(this, audioUrl, new FileAsyncHttpResponseHandler(file) {

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {

                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, File file) {
                    // 更新 音频的 audioLocalUrl
                    DatabaseManager.getInstance(LocalCommentService.this).updateDiscoverAudioLocalPath(file.getAbsolutePath(), diaryId);
                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {

                }
            });
        }
    }

    // 创建 日记 对象
    private Discover setupDiscover(DiscoverContentResponse response) {
        Discover discover = new Discover();
        discover.setDiaryID(response.getDiaryId());
        discover.setIsDelete(response.getState() == 0);
        discover.setAudio(response.getAudio());
        discover.setUserHeadUrl(response.getHeadUrl());
        discover.setBabyID(response.getBabyId());
        discover.setBabyName(response.getBabyName());
        discover.setCreateTS(response.getCreateTS());
        discover.setDuration(response.getMediaLength());
        discover.setGrowthStageID(response.getState());
        discover.setMemberName(response.getName());
        discover.setMilestone(response.getMilestone());
        discover.setScreenshot(response.getScreenshot());
        discover.setText(response.getText());
        discover.setTheme(response.getTheme());
        discover.setNickName(response.getNickName());
        discover.setType(response.getType());
        // 接口没返回 UserId，不在更新 UserID
        discover.setUserID(response.getUserId());
        discover.setDiaryFrom(3); // 来自最新评论
        discover.setVideo(response.getVideo());
        discover.setBabyHeadUrl(response.getBabyHeadUrl());
        return discover;
    }

    // 保存日记到本地数据库
    private void storeDiscoverToLocal(DiscoverContentResponse response) {
        if(response != null) {
            Discover discover = setupDiscover(response);
            if(discover.getIsDelete()) {
                DatabaseManager.getInstance(this).deleteDiscover(discover.getDiaryID());
            } else {
                DatabaseManager.getInstance(this).insertOrReplaceDiscover(discover, response.getPhotos());
            }
        }
    }

    // 保存日记的评论到本地的数据库
    private void storeDiscoverCommentToLocal(DiscoverResponse response, LoginInfo loginInfo) {
        // 删除日记之前的评论
        DatabaseManager.getInstance(this).deleteDiscoverComments(response.getContent().getDiaryId());

        ArrayList<DiscoverSaveComment> comments = new ArrayList<>();
        if(response.getComment() != null) {
            addComment(response.getComment(), comments, 2, loginInfo.getUserID());
        }
        if(response.getLike() != null) {
            addComment(response.getLike(), comments, 2, loginInfo.getUserID());
        }
        DatabaseManager.getInstance(this).insertOrReplaceDiscoverSaveCommentInTx(comments);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
